import $ from "jquery";
import "../../scss/forgetPassword.scss";
require("../utils/remove_ad");
require("../utils/oldcommon/layer");
var main = {
  checkPhone: function(arg) {
    // 验证手机号
    var phone = arg.val();
    if (!/^1[34578]\d{9}$/.test(phone)) {
      main.dialog("手机格式不正确");
      return false;
    } else {
      return true;
    }
  },
  dialog: function(msg) {
    // 弹窗消息
    $(".js_tooltips")
      .text(msg)
      .css("display", "block");
    setTimeout(function() {
      $(".js_tooltips").css("display", "none");
    }, 5000);
  },
  setTime: function(val, time) {
    // 设置倒计时间
    if (time === 0) {
      $(val).click(clickVerifyCode);
      $(val)
        .css("color", "#0099ff")
        .text("获取验证码");
      // 如果不写return将会一直重复执行这边代码
      return;
    } else {
      $(val)
        .css("color", "#969696")
        .text(time + "s后重发");
      time--;
      $(val).unbind();
    }
    setTimeout(function() {
      main.setTime(val, time);
    }, 1000);
  }
};
// 点击获取验证码函数
function clickVerifyCode() {
  var verifyPhone = $(".verify_phone");
  if (main.checkPhone(verifyPhone)) {
    var countdown = 60;
    $.ajax({
      type: "POST",
      data: {
        mobile: verifyPhone.val()
      },
      url: "/user/pre_reg1/" + verifyPhone.val().trim(),
      dataType: "json",
      success: function(data) {
        if (data.status) {
          main.dialog("验证短信已经发送至" + $(".verify_phone").val() + "，请注意查收.");
          main.setTime(".verify_code", countdown);
        } else {
          main.dialog(data.msg);
        }
      }
    });
  }
}

$(".verify_code").click(clickVerifyCode); // 点击获取验证码
$(".sure_modify").click(function() {
  var verifyPhone = $(".verify_phone").val();
  var verifyCode = $("#verifyCode").val();
  var newPassword = $("#newPassword").val();
  if (
    main.checkPhone($(".verify_phone")) &&
    verifyCode.length > 0 &&
    newPassword.length >= 6
  ) {
    $.ajax({
      type: "post",
      data: {
        mobile: verifyPhone,
        verify_code: verifyCode,
        newPassword: newPassword
      },
      url: "/user/forgetVerify/" + verifyPhone,
      dataType: "json",
      success: function(data) {
        console.log(data);
        if (data.status) {
          layer.open({
            content: "修改成功。",
            btn: "确定",
            yes: function() {
              setTimeout(function() {
                if (data.data.returnUri) {
                  window.location.href = data.data.returnUri;
                } else {
                  window.location.href = "/center";
                }
              }, 1000);
            }
          });
        } else {
          layer.open({
            content: data.msg,
            btn: "确定"
          });
        }
      },
      error: function() {
        console.log("error");
      }
    });
  }
});
